<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getCarDetail, getCarAvailability, getCarTypes, addToFavorites, removeFromFavorites, checkFavoriteStatus } from '@/api/car'
import { ArrowLeft, Calendar, Star, StarFilled } from '@element-plus/icons-vue'
import { useUserInfoStore } from '@/stores/userInfo'

const route = useRoute()
const router = useRouter()
const userInfoStore = useUserInfoStore()

// 响应式数据
const car = ref({})
const carTypes = ref([])
const unavailableDates = ref([])
const loading = ref(false)
const calendarValue = ref(new Date())

// 收藏相关数据
const isFavorited = ref(false)
const favoriteLoading = ref(false)

// 获取车辆详情
const loadCarDetail = async () => {
  loading.value = true
  try {
    const carId = route.params.id
    const res = await getCarDetail(carId)
    // 由于request拦截器已经处理了成功响应，这里直接使用数据
    car.value = res.data || {}

    // 同时获取可租日期和收藏状态
    await Promise.all([
      loadCarAvailability(carId),
      checkFavorite(carId)
    ])
  } catch (error) {
    ElMessage.error('获取车辆详情失败')
    console.error('获取车辆详情失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取车辆可租日期
const loadCarAvailability = async (carId) => {
  try {
    console.log('正在获取车辆可租日期，carId:', carId)
    const res = await getCarAvailability(carId)
    // 由于request拦截器已经处理了成功响应，这里直接使用数据
    unavailableDates.value = res.data || []
    console.log('成功获取可租日期:', unavailableDates.value)
  } catch (error) {
    console.error('获取可租日期失败:', error)
    // 不显示错误消息，因为这不是关键功能
  }
}

// 获取车辆类型
const loadCarTypes = async () => {
  try {
    const res = await getCarTypes()
    // 由于request拦截器已经处理了成功响应，这里直接使用数据
    carTypes.value = res.data || []
  } catch (error) {
    console.error('获取车辆类型失败:', error)
  }
}

// 获取车型名称
const getTypeName = (typeId) => {
  const type = carTypes.value.find(t => t.id == typeId)
  return type ? type.name : '未知'
}

// 返回列表
const goBack = () => {
  router.push('/user/carBrowse')
}

// 立即租车
const rentNow = () => {
  if (car.value.status !== 0) {
    ElMessage.warning('该车辆当前不可租用')
    return
  }

  // 跳转到租车流程页面
  router.push(`/user/rental/process/${route.params.id}`)
}

// 检查收藏状态
const checkFavorite = async (carId) => {
  try {
    const res = await checkFavoriteStatus({
      userId: userInfoStore.userInfo?.id || '', // 从用户状态获取当前登录用户ID
      carId: carId
    })
    isFavorited.value = res.data || false
  } catch (error) {
    console.error('检查收藏状态失败:', error)
  }
}

// 切换收藏状态
const toggleFavorite = async () => {
  favoriteLoading.value = true

  try {
    const carId = route.params.id
    const userId = userInfoStore.userInfo?.id || '' // 从用户状态获取当前登录用户ID

    if (isFavorited.value) {
      // 取消收藏
      await removeFromFavorites({
        userId: userId,
        carId: carId
      })
      isFavorited.value = false
      ElMessage.success('已取消收藏')
    } else {
      // 添加收藏
      await addToFavorites({
        userId: userId,
        carId: carId
      })
      isFavorited.value = true
      ElMessage.success('收藏成功')
    }
  } catch (error) {
    ElMessage.error('操作失败，请重试')
    console.error('收藏操作失败:', error)
  } finally {
    favoriteLoading.value = false
  }
}

// 日历禁用日期函数
const disabledDate = (time) => {
  const dateStr = time.toISOString().split('T')[0]
  return unavailableDates.value.includes(dateStr) || time.getTime() < Date.now() - 8.64e7
}

onMounted(() => {
  loadCarTypes()
  loadCarDetail()
})
</script>

<template>
  <div class="car-detail" v-loading="loading">
    <!-- 头部导航 -->
    <div class="header">
      <el-button :icon="ArrowLeft" @click="goBack">返回列表</el-button>
      <h2>车辆详情</h2>
    </div>

    <div class="detail-content" v-if="car.id">
      <el-row :gutter="30">
        <!-- 左侧：车辆图片和基本信息 -->
        <el-col :span="10">
          <div class="left-content">
            <el-card shadow="never" class="main-info-card">
              <div class="car-image">
<!--                <img :src="car.images || '/default-car.jpg'" :alt="car.brand + ' ' + car.model" />-->
                <img :src="`/api/file/download.do?filename=${car.images}`"
                     :alt="car.brand + ' ' + car.model" />
              </div>

              <div class="car-basic-info">
                <h1 class="car-title">{{ car.brand }} {{ car.model }}</h1>
                <div class="car-price">
                  <span class="price">¥{{ car.dailyRent }}</span>
                  <span class="unit">/天</span>
                </div>

                <div class="car-status">
                  <el-tag :type="car.status === 0 ? 'success' : 'danger'">
                    {{ car.status === 0 ? '可租用' : '已租出' }}
                  </el-tag>
                </div>

                <div class="action-buttons">
                  <el-row :gutter="10">
                    <el-col :span="16">
                      <el-button
                        type="primary"
                        size="large"
                        :disabled="car.status !== 0"
                        @click="rentNow"
                        style="width: 100%"
                      >
                        {{ car.status === 0 ? '立即租车' : '暂不可租' }}
                      </el-button>
                    </el-col>
                    <el-col :span="8">
                      <el-button
                        :type="isFavorited ? 'danger' : 'default'"
                        size="large"
                        @click="toggleFavorite"
                        style="width: 100%"
                        :loading="favoriteLoading"
                      >
                        <el-icon>
                          <component :is="isFavorited ? 'StarFilled' : 'Star'" />
                        </el-icon>
                        {{ isFavorited ? '已收藏' : '收藏' }}
                      </el-button>
                    </el-col>
                  </el-row>
                  <div v-if="car.status !== 0" class="unavailable-tip">
                    <el-text type="info" size="small">
                      该车辆当前已被租出，暂时无法预订
                    </el-text>
                  </div>
                </div>
              </div>
            </el-card>

            <!-- 车辆参数 -->
            <el-card shadow="never" class="params-card">
              <template #header>
                <span>车辆参数</span>
              </template>

              <div class="params-list">
                <div class="param-item">
                  <span class="label">品牌：</span>
                  <span class="value">{{ car.brand }}</span>
                </div>
                <div class="param-item">
                  <span class="label">型号：</span>
                  <span class="value">{{ car.model }}</span>
                </div>
                <div class="param-item">
                  <span class="label">车型：</span>
                  <span class="value">{{ getTypeName(car.typeId) }}</span>
                </div>
                <div class="param-item">
                  <span class="label">颜色：</span>
                  <span class="value">{{ car.color }}</span>
                </div>
                <div class="param-item">
                  <span class="label">车牌号：</span>
                  <span class="value">{{ car.licensePlate }}</span>
                </div>
                <div class="param-item">
                  <span class="label">日租金：</span>
                  <span class="value price-highlight">¥{{ car.dailyRent }}/天</span>
                </div>
              </div>
            </el-card>
          </div>
        </el-col>

        <!-- 右侧：可租日期 -->
        <el-col :span="14">
          <!-- 可租日期日历 -->
          <el-card shadow="never" class="calendar-card">
            <template #header>
              <div class="calendar-header">
                <el-icon><Calendar /></el-icon>
                <span>可租日期</span>
              </div>
            </template>
            
            <div class="calendar-content">
              <!-- 可租日期统计 -->
              <div v-if="unavailableDates.length > 0" class="availability-summary">
                <el-alert
                  :title="`本月共有 ${unavailableDates.length} 个日期已被预订`"
                  type="info"
                  :closable="false"
                  show-icon>
                </el-alert>
              </div>

              <el-calendar v-model="calendarValue">
                <template #date-cell="{ data }">
                  <div class="calendar-day" :class="{
                    'unavailable': unavailableDates.includes(data.day),
                    'available': !unavailableDates.includes(data.day) && new Date(data.day).getTime() >= Date.now() - 8.64e7,
                    'past': new Date(data.day).getTime() < Date.now() - 8.64e7,
                    'today': data.isSelected
                  }">
                    <span class="day-number">{{ data.day.split('-').pop() }}</span>
                    <span v-if="unavailableDates.includes(data.day)" class="status-text">已预订</span>
                    <span v-else-if="new Date(data.day).getTime() >= Date.now() - 8.64e7" class="status-text">可租</span>
                  </div>
                </template>
              </el-calendar>
              
              <div class="calendar-legend">
                <div class="legend-item">
                  <span class="legend-color available"></span>
                  <span>✅ 可租用</span>
                </div>
                <div class="legend-item">
                  <span class="legend-color unavailable"></span>
                  <span>❌ 已预订</span>
                </div>
                <div class="legend-item">
                  <span class="legend-color past"></span>
                  <span>⏰ 过去日期</span>
                </div>
                <div class="legend-item">
                  <span class="legend-color today"></span>
                  <span>📅 今天</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 空状态 -->
    <el-empty v-else-if="!loading" description="车辆不存在" />
  </div>
</template>

<style lang="scss" scoped>
.car-detail {
  padding: 20px;

  .header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    gap: 15px;

    h2 {
      margin: 0;
      color: #303133;
    }
  }

  .detail-content {
    :deep(.el-row) {
      align-items: stretch;
    }

    :deep(.el-col) {
      display: flex;
      flex-direction: column;
    }

    .left-content {
      display: flex;
      flex-direction: column;
      height: 100%;
      gap: 20px;

      .main-info-card {
        flex: 1.2;
        display: flex;
        flex-direction: column;

        :deep(.el-card__body) {
          display: flex;
          flex-direction: column;
          height: 100%;
        }

        .car-image {
          width: 100%;
          height: 160px;
          border-radius: 8px;
          overflow: hidden;
          margin-bottom: 15px;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }
      }

      .params-card {
        flex: 0.8;
        display: flex;
        flex-direction: column;

        :deep(.el-card__body) {
          flex: 1;
          display: flex;
          flex-direction: column;
        }
      }
    }

    .car-basic-info {
      .car-title {
        font-size: 24px;
        font-weight: bold;
        margin: 0 0 15px 0;
        color: #303133;
      }

      .car-price {
        margin-bottom: 15px;

        .price {
          font-size: 28px;
          font-weight: bold;
          color: #e6a23c;
        }

        .unit {
          font-size: 16px;
          color: #909399;
          margin-left: 5px;
        }
      }

      .car-status {
        margin-bottom: 20px;
      }

      .action-buttons {
        .el-button {
          height: 50px;
          font-size: 16px;
        }

        .unavailable-tip {
          margin-top: 10px;
          text-align: center;
          padding: 8px;
          background-color: #f5f7fa;
          border-radius: 4px;
          border-left: 3px solid #909399;
        }
      }
    }

    .params-card {
      .params-list {
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
        height: 100%;
        padding-top: 10px;

        .param-item {
          display: flex;
          justify-content: space-between;
          padding: 3px 0;
          border-bottom: 1px solid #f0f0f0;

          &:last-child {
            border-bottom: none;
          }

          .label {
            color: #606266;
            font-weight: 500;
            min-width: 80px;
            font-size: 13px;
            line-height: 1.4;
          }

          .value {
            color: #303133;
            text-align: right;
            font-size: 13px;
            line-height: 1.4;

            &.price-highlight {
              color: #e6a23c;
              font-weight: bold;
            }
          }
        }
      }
    }

    .calendar-card {
      .calendar-header {
        display: flex;
        align-items: center;
        gap: 8px;
      }

      .calendar-content {
        .availability-summary {
          margin-bottom: 20px;
        }

        .calendar-day {
          width: 100%;
          height: 60px;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          border-radius: 8px;
          margin: 2px;
          transition: all 0.3s ease;
          position: relative;

          .day-number {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 2px;
          }

          .status-text {
            font-size: 10px;
            font-weight: normal;
          }

          &.available {
            background-color: #f0f9ff;
            border: 2px solid #67c23a;
            color: #67c23a;

            &:hover {
              background-color: #e8f5e8;
              transform: scale(1.05);
            }
          }

          &.unavailable {
            background-color: #fef0f0;
            border: 2px solid #f56c6c;
            color: #f56c6c;

            .status-text {
              color: #f56c6c;
            }
          }

          &.past {
            background-color: #f5f5f5;
            color: #c0c4cc;
            border: 1px solid #e4e7ed;
          }

          &.today {
            background-color: #409eff;
            color: white;
            border: 2px solid #409eff;

            .status-text {
              color: white;
            }
          }
        }

        .calendar-legend {
          display: flex;
          gap: 15px;
          margin-top: 20px;
          justify-content: center;
          flex-wrap: wrap;

          .legend-item {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
            padding: 8px 12px;
            background-color: #f8f9fa;
            border-radius: 6px;
            border: 1px solid #e9ecef;

            .legend-color {
              width: 20px;
              height: 20px;
              border-radius: 6px;
              border: 2px solid;

              &.available {
                background-color: #f0f9ff;
                border-color: #67c23a;
              }

              &.unavailable {
                background-color: #fef0f0;
                border-color: #f56c6c;
              }

              &.past {
                background-color: #f5f5f5;
                border-color: #c0c4cc;
              }

              &.today {
                background-color: #409eff;
                border-color: #409eff;
              }
            }
          }
        }
      }
    }
  }
}
</style>
